<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/5/29
 * Time: 15:06
 */

namespace app\api\service;



use Endroid\QrCode\QrCode;

class ImageService
{

    private static $_service;
    public $savePath;
    public $webPath;
    public $x = 230;
    public $y = 915;
    public $saveQrcodePuth = './qrcode/member/';


    public function __construct()
    {
        $this->savePath = './qrcode';
        $this->webPath  = '/qrcode/';
    }

    public static function getInstance()
    {
        if( null == self::$_service ){
            self::$_service = new ImageService();
        }
        return self::$_service;
    }

    public function createQRcode($savePath, $qrData = 'PHP QR Code :)', $qrLevel = 'L', $qrSize = 4, $savePrefix = 'qrcode')
    {
        if (!isset($savePath)) return '';
        $PNG_TEMP_DIR = $savePath;
        if (!file_exists($PNG_TEMP_DIR)) {
            mkdir($PNG_TEMP_DIR);
        }
        $filename = $PNG_TEMP_DIR . 'test.png';
        $errorCorrectionLevel = 'L';
        if (isset($qrLevel) && in_array($qrLevel, ['L', 'M', 'Q', 'H'])) {
            $errorCorrectionLevel = $qrLevel;
        }
        $matrixPointSize = 4;
        if (isset($qrSize)) {
            $matrixPointSize = min(max((int)$qrSize, 1), 10);
        }
        if (isset($qrData)) {
            if (trim($qrData) == '') {
                die('data cannot be empty!');
            }
            $filename = $PNG_TEMP_DIR . $savePrefix . md5($qrData . '|' . $errorCorrectionLevel . '|' . $matrixPointSize.'|'.time()) .mt_rand(0, 0xffff). '.png';

            \PHPQRCode\QRcode::png($qrData, $filename, $errorCorrectionLevel, $matrixPointSize, 2);
        } else {

            \PHPQRCode\QRcode::png('PHP QR Code :)', $filename, $errorCorrectionLevel, $matrixPointSize, 2);
        }
        if (file_exists($PNG_TEMP_DIR . basename($filename)))
            return basename($filename);
        else
            return FALSE;
    }
}